package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 小程序登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        //1、根据授权码去换openid
        String openId = getOpenId(userLoginDTO.getCode());

        //2、根据openid查询用户信息
        User user = userMapper.selectByOpenId(openId);

        //3、如果用户不存在，则新增用户
        if (user == null) {
            user = new User();
            //用户不存在，新增用户
            BeanUtils.copyProperties(userLoginDTO, user);
            user.setOpenid(openId);
            userMapper.save(user);
        }

        //4、生成token - JWT令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String jwtToken = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        //5、封装VO返回
        return UserLoginVO.builder().id(user.getId()).token(jwtToken).openid(openId).build();
    }

    /**
     * 调用微信后台接口：获取openid
     *
     * @return
     */
    private String getOpenId(String code) {
        Map paramMap = new HashMap();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");

        log.info("小程序登录，参数：{}", paramMap);

        String resultJson = HttpClientUtil.doGet(weChatProperties.getJscode2sessionUrl(), paramMap);
        log.info("小程序登录，resultJson ：{}", resultJson);

        JSONObject jsonObject = JSON.parseObject(resultJson);
        String openId = jsonObject.getString("openid");

        log.info("小程序登录，参数：{}，获取到的openId：{}", paramMap, openId);
        return openId;
    }
}
